package com.king.oa.service.impl;

import java.util.List;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.king.oa.base.DaoSupportImpl;
import com.king.oa.domain.Forum;
import com.king.oa.service.ForumService;

@Service
@Transactional
@SuppressWarnings("unchecked")
public class ForumServiceImpl extends DaoSupportImpl<Forum> implements ForumService {

	@Override
	public List<Forum> findAll() {
		
		return getSession().createQuery(//
				"FROM Forum f ORDER BY f.position")//
				.list();
	}
	
	@Override
	public void save(Forum forum) {
		//保存
		super.save(forum);
		//设置position的值
		forum.setPosition(forum.getId().intValue());
		
	}
	
	@Override
	public void moveUp(Long id) {
		//找出相关的Forum
		Forum forum = findById(id);
		Forum other = (Forum) getSession().createQuery(//上面的Forum
				"FROM Forum f WHERE f.position<? ORDER BY f.position DESC")//
				.setParameter(0, forum.getPosition())//
				.setFirstResult(0)//
				.setMaxResults(1)//
				.uniqueResult();//
		//判断是否还可以上移
		if(other==null){
			return;
		}
		
		//交换position的值
		int temp = other.getPosition();
		other.setPosition(forum.getPosition());
		forum.setPosition(temp);
		
		//更新到数据库,可以不写，因为对象现在是持久化状态
		getSession().update(forum);
		getSession().update(other);
		
	}

	@Override
	public void moveDown(Long id) {
		//找出相关的Forum
		Forum forum = findById(id);
		Forum other = (Forum) getSession().createQuery(//下面的Forum
				"FROM Forum f WHERE f.position>? ORDER BY f.position ASC")//
				.setParameter(0, forum.getPosition())//
				.setFirstResult(0)//
				.setMaxResults(1)//
				.uniqueResult();//
		
		//判断是否还可以下移
		if(other==null){
			return;
		}
		
		//交换position的值
		int temp = other.getPosition();
		other.setPosition(forum.getPosition());
		forum.setPosition(temp);
		
		//更新到数据库,可以不写，因为对象现在是持久化状态
		getSession().update(forum);
		getSession().update(other);
	}

}
